package org.example;/*
 * title:
 * author:
 * date:
 * description:
 * */

public class sparsearray {
    public static void main(String[] args) {
        //原始的二维数组
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        for (int i = 0; i < chessArr1.length; i++) {
            for (int j = 0; j < chessArr1[0].length; j++) {
                System.out.print(chessArr1[i][j] + " ");
            }
            System.out.println();
        }

        int sum = 0;
        for (int i = 0; i < chessArr1.length; i++) {
            for (int j = 0; j < chessArr1[0].length; j++) {
                if (chessArr1[i][j] != 0) {
                    sum++;
                }
            }
        }
        System.out.println(sum);

        //用sum创建sparsearray
        int[][] sparsearray = new int[sum + 1][3];
        sparsearray[0][0] = chessArr1.length;
        sparsearray[0][1] = chessArr1.length;
        sparsearray[0][2] = sum;
        int row = 0;
        int col = 0;
        for (int i = 0; i < chessArr1.length; i++) {
            for (int j = 0; j < chessArr1[0].length; j++) {
                if (chessArr1[i][j] != 0) {
                    sparsearray[++row][0] = i;
                    sparsearray[row][1] = j;
                    sparsearray[row][2] = chessArr1[i][j];
                }
            }
        }

        for (int i = 0; i < sparsearray.length; i++) {
            for (int j = 0; j < sparsearray[0].length; j++) {
                System.out.print(sparsearray[i][j] + " ");
            }
            System.out.println();
        }
        //返回去
        int[][] chessArr2 = new int[sparsearray[0][0]][sparsearray[0][1]];

        for (int i = 1; i < sparsearray.length; i++) {
            chessArr2[sparsearray[i][0]][sparsearray[i][1]] = sparsearray[i][2];
        }
        for (int i = 0; i < chessArr2.length; i++) {
            for (int j = 0; j < chessArr2[0].length; j++) {
                System.out.print(chessArr2[i][j] + " ");
            }
            System.out.println();
        }
    }
}
